package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.net.CacheRequest;
import java.util.List;

@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 关键字联想词查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAssociate(UserSearchDto dto) {
        
        //检查参数
        if(StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //分页检查
        int pageSize = dto.getPageSize();
        if(pageSize > 20){
            pageSize = 20;
        }

        //模糊查询
        List<ApAssociateWords> associateWords = mongoTemplate.find(Query.query(Criteria.where("associateWords")
                .regex("^.*" + dto.getSearchWords() + ".*$")).limit(pageSize), ApAssociateWords.class);

        return ResponseResult.okResult(associateWords);
        
    }
}